<!DOCTYPE html>
<html>
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="utf-8">
  

  
  <title>SpringBoot web应用中统一异常处理 | Hexo</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <meta name="description" content="我们在做Web应用的时候，请求处理过程中发生错误是非常常见的情况。Spring Boot提供了一个默认的映射：/error，当处理中抛出异常之后，会转到该请求中处理，并且该请求有一个全局的错误页面用来展示异常内容。">
<meta name="keywords" content="springboot">
<meta property="og:type" content="article">
<meta property="og:title" content="SpringBoot web应用中统一异常处理">
<meta property="og:url" content="http://yoursite.com/2018/10/12/2018-06-17-SpringBoot web应用中统一异常处理/index.html">
<meta property="og:site_name" content="Hexo">
<meta property="og:description" content="我们在做Web应用的时候，请求处理过程中发生错误是非常常见的情况。Spring Boot提供了一个默认的映射：/error，当处理中抛出异常之后，会转到该请求中处理，并且该请求有一个全局的错误页面用来展示异常内容。">
<meta property="og:locale" content="default">
<meta property="og:image" content="http://p1aoqp63y.bkt.clouddn.com/241FA8A7-2493-44B9-A0A3-79849656074A.png">
<meta property="og:image" content="http://p1aoqp63y.bkt.clouddn.com/QQ%E6%88%AA%E5%9B%BE20180617172450.png">
<meta property="og:updated_time" content="2018-11-01T14:24:04.952Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="SpringBoot web应用中统一异常处理">
<meta name="twitter:description" content="我们在做Web应用的时候，请求处理过程中发生错误是非常常见的情况。Spring Boot提供了一个默认的映射：/error，当处理中抛出异常之后，会转到该请求中处理，并且该请求有一个全局的错误页面用来展示异常内容。">
<meta name="twitter:image" content="http://p1aoqp63y.bkt.clouddn.com/241FA8A7-2493-44B9-A0A3-79849656074A.png">
  
    <link rel="alternate" href="/org/atom.xml" title="Hexo" type="application/atom+xml">
  
  
    <link rel="icon" href="/favicon.png">
  
  
    <link href="//fonts.googleapis.com/css?family=Source+Code+Pro" rel="stylesheet" type="text/css">
  
  <link rel="stylesheet" href="/org/css/style.css">
</head>
</html>
<body>
  <div id="container">
    <div id="wrap">
      <header id="header">
  <div id="banner"></div>
  <div id="header-outer" class="outer">
    <div id="header-title" class="inner">
      <h1 id="logo-wrap">
        <a href="/org/" id="logo">Hexo</a>
      </h1>
      
    </div>
    <div id="header-inner" class="inner">
      <nav id="main-nav">
        <a id="main-nav-toggle" class="nav-icon"></a>
        
          <a class="main-nav-link" href="/org/">Home</a>
        
          <a class="main-nav-link" href="/org/archives">Archives</a>
        
      </nav>
      <nav id="sub-nav">
        
          <a id="nav-rss-link" class="nav-icon" href="/org/atom.xml" title="RSS Feed"></a>
        
        <a id="nav-search-btn" class="nav-icon" title="Search"></a>
      </nav>
      <div id="search-form-wrap">
        <form action="//google.com/search" method="get" accept-charset="UTF-8" class="search-form"><input type="search" name="q" class="search-form-input" placeholder="Search"><button type="submit" class="search-form-submit">&#xF002;</button><input type="hidden" name="sitesearch" value="http://yoursite.com"></form>
      </div>
    </div>
  </div>
</header>
      <div class="outer">
        <section id="main"><article id="post-2018-06-17-SpringBoot web应用中统一异常处理" class="article article-type-post" itemscope="" itemprop="blogPost">
  <div class="article-meta">
    <a href="/org/2018/10/12/2018-06-17-SpringBoot web应用中统一异常处理/" class="article-date">
  <time datetime="2018-10-12T09:03:30.000Z" itemprop="datePublished">2018-10-12</time>
</a>
    
  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 class="article-title" itemprop="name">
      SpringBoot web应用中统一异常处理
    </h1>
  

      </header>
    
    <div class="article-entry" itemprop="articleBody">
      
        <p>我们在做Web应用的时候，请求处理过程中发生错误是非常常见的情况。Spring Boot提供了一个默认的映射：<code>/error</code>，当处理中抛出异常之后，会转到该请求中处理，并且该请求有一个全局的错误页面用来展示异常内容。 </p>
<a id="more"></a>
<p>选择一个之前实现过的Web应用（<a href="http://git.oschina.net/didispace/SpringBoot-Learning/tree/master/Chapter3-1-2" target="_blank" rel="noopener">Chapter3-1-2</a>）为基础，启动该应用，访问一个不存在的URL，或是修改处理内容，直接抛出异常，如： </p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">@RequestMapping(&quot;/hello&quot;)</span><br><span class="line">public String hello() throws Exception &#123;</span><br><span class="line">    throw new Exception(&quot;发生错误&quot;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>此时，可以看到类似下面的报错页面，该页面就是Spring Boot提供的默认error映射页面。 </p>
<p><img src="http://p1aoqp63y.bkt.clouddn.com/241FA8A7-2493-44B9-A0A3-79849656074A.png" alt="img"></p>
<h2 id="统一异常处理"><a href="#统一异常处理" class="headerlink" title="统一异常处理"></a>统一异常处理</h2><p>虽然，Spring Boot中实现了默认的error映射，但是在实际应用中，上面你的错误页面对用户来说并不够友好，我们通常需要去实现我们自己的异常提示 </p>
<ul>
<li>创建全局异常处理类：通过使用<code>@ControllerAdvice</code>定义统一的异常处理类，而不是在每个Controller中逐个定义。<code>@ExceptionHandler</code>用来定义函数针对的异常类型，最后将Exception对象和请求URL映射到<code>error.html</code>中</li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">@ControllerAdvice</span><br><span class="line">class GlobalExceptionHandler &#123;</span><br><span class="line"></span><br><span class="line">    public static final String DEFAULT_ERROR_VIEW = &quot;error&quot;;</span><br><span class="line"></span><br><span class="line">    @ExceptionHandler(value = Exception.class)</span><br><span class="line">    public ModelAndView defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception &#123;</span><br><span class="line">        ModelAndView mav = new ModelAndView();</span><br><span class="line">        mav.addObject(&quot;exception&quot;, e);</span><br><span class="line">        mav.addObject(&quot;url&quot;, req.getRequestURL());</span><br><span class="line">        mav.setViewName(DEFAULT_ERROR_VIEW);</span><br><span class="line">        return mav;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ul>
<li>实现<code>error.html</code>页面展示：在<code>templates</code>目录下创建<code>error.html</code>，将请求的URL和Exception对象的message输出。</li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">&lt;!DOCTYPE html&gt;</span><br><span class="line">&lt;html&gt;</span><br><span class="line">&lt;head lang=&quot;en&quot;&gt;</span><br><span class="line">    &lt;meta charset=&quot;UTF-8&quot; /&gt;</span><br><span class="line">    &lt;title&gt;统一异常处理&lt;/title&gt;</span><br><span class="line">&lt;/head&gt;</span><br><span class="line">&lt;body&gt;</span><br><span class="line">    &lt;h1&gt;Error Handler&lt;/h1&gt;</span><br><span class="line">    &lt;div th:text=&quot;$&#123;url&#125;&quot;&gt;&lt;/div&gt;</span><br><span class="line">    &lt;div th:text=&quot;$&#123;exception.message&#125;&quot;&gt;&lt;/div&gt;</span><br><span class="line">&lt;/body&gt;</span><br><span class="line">&lt;/html&gt;</span><br></pre></td></tr></table></figure>
<p>启动该应用，访问：<code>http://localhost:8080/hello</code>，可以看到如下错误提示页面。 </p>
<p><img src="http://p1aoqp63y.bkt.clouddn.com/QQ%E6%88%AA%E5%9B%BE20180617172450.png" alt="ig"></p>
<p><em>通过实现上述内容之后，我们只需要在Controller中抛出Exception，当然我们可能会有多种不同的Exception。然后在@ControllerAdvice类中，根据抛出的具体Exception类型匹配@ExceptionHandler中配置的异常类型来匹配错误映射和处理。</em> </p>
<h2 id="返回JSON格式"><a href="#返回JSON格式" class="headerlink" title="返回JSON格式"></a>返回JSON格式</h2><p>在上述例子中，通过<code>@ControllerAdvice</code>统一定义不同Exception映射到不同错误处理页面。而当我们要实现RESTful API时，返回的错误是JSON格式的数据，而不是HTML页面，这时候我们也能轻松支持。</p>
<p>本质上，只需在<code>@ExceptionHandler</code>之后加入<code>@ResponseBody</code>，就能让处理函数return的内容转换为JSON格式。</p>
<p>下面以一个具体示例来实现返回JSON格式的异常处理。</p>
<ul>
<li>创建统一的JSON返回对象，code：消息类型，message：消息内容，url：请求的url，data：请求返回的数据</li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">public class ErrorInfo&lt;T&gt; &#123;</span><br><span class="line"></span><br><span class="line">    public static final Integer OK = 0;</span><br><span class="line">    public static final Integer ERROR = 100;</span><br><span class="line"></span><br><span class="line">    private Integer code;</span><br><span class="line">    private String message;</span><br><span class="line">    private String url;</span><br><span class="line">    private T data;</span><br><span class="line"></span><br><span class="line">    // 省略getter和setter</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ul>
<li>创建一个自定义异常，用来实验捕获该异常，并返回json</li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">public class MyException extends Exception &#123;</span><br><span class="line"></span><br><span class="line">    public MyException(String message) &#123;</span><br><span class="line">        super(message);</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ul>
<li><code>Controller</code>中增加json映射，抛出<code>MyException</code>异常</li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">@Controller</span><br><span class="line">public class HelloController &#123;</span><br><span class="line"></span><br><span class="line">    @RequestMapping(&quot;/json&quot;)</span><br><span class="line">    public String json() throws MyException &#123;</span><br><span class="line">        throw new MyException(&quot;发生错误2&quot;);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ul>
<li>为<code>MyException</code>异常创建对应的处理</li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">@ControllerAdvice</span><br><span class="line">public class GlobalExceptionHandler &#123;</span><br><span class="line"></span><br><span class="line">    @ExceptionHandler(value = MyException.class)</span><br><span class="line">    @ResponseBody</span><br><span class="line">    public ErrorInfo&lt;String&gt; jsonErrorHandler(HttpServletRequest req, MyException e) throws Exception &#123;</span><br><span class="line">        ErrorInfo&lt;String&gt; r = new ErrorInfo&lt;&gt;();</span><br><span class="line">        r.setMessage(e.getMessage());</span><br><span class="line">        r.setCode(ErrorInfo.ERROR);</span><br><span class="line">        r.setData(&quot;Some Data&quot;);</span><br><span class="line">        r.setUrl(req.getRequestURL().toString());</span><br><span class="line">        return r;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ul>
<li>启动应用，访问：<a href="http://localhost:8080/json%EF%BC%8C%E5%8F%AF%E4%BB%A5%E5%BE%97%E5%88%B0%E5%A6%82%E4%B8%8B%E8%BF%94%E5%9B%9E%E5%86%85%E5%AE%B9%EF%BC%9A" target="_blank" rel="noopener">http://localhost:8080/json，可以得到如下返回内容：</a></li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">    code: 100，</span><br><span class="line">    data: &quot;Some Data&quot;，</span><br><span class="line">    message: &quot;发生错误2&quot;，</span><br><span class="line">    url: &quot;http://localhost:8080/json&quot;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>至此，已完成在Spring Boot中创建统一的异常处理，实际实现还是依靠Spring MVC的注解，更多更深入的使用可参考Spring MVC的文档。</p>
<h2 id="代码示例"><a href="#代码示例" class="headerlink" title="代码示例"></a>代码示例</h2><p><a href="https://gitee.com/anweb/SpringBoot-Learning" target="_blank" rel="noopener">源码下载-Chapter-3-1-6</a></p>

      
    </div>
    <footer class="article-footer">
      <a data-url="http://yoursite.com/2018/10/12/2018-06-17-SpringBoot web应用中统一异常处理/" data-id="cjoztxu58001v1wijs59ck2se" class="article-share-link">Share</a>
      
      
  <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/org/tags/springboot/">springboot</a></li></ul>

    </footer>
  </div>
  
    
<nav id="article-nav">
  
    <a href="/org/2018/10/12/2018-05-03-SVN文档目录规范/" id="article-nav-newer" class="article-nav-link-wrap">
      <strong class="article-nav-caption">Newer</strong>
      <div class="article-nav-title">
        
          SVN文档规划
        
      </div>
    </a>
  
  
    <a href="/org/2018/10/12/2018-06-17-SpringBoot web开发-Freemaker模板引擎/" id="article-nav-older" class="article-nav-link-wrap">
      <strong class="article-nav-caption">Older</strong>
      <div class="article-nav-title">SpringBoot web开发-Freemaker模板引擎</div>
    </a>
  
</nav>

  
</article>

</section>
        
          <aside id="sidebar">
  
    

  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Tags</h3>
    <div class="widget">
      <ul class="tag-list"><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/SVN/">SVN</a></li><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/Spring-secrity/">Spring-secrity</a></li><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/hexo/">hexo</a></li><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/hibenrate/">hibenrate</a></li><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/jekyll/">jekyll</a></li><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/jenkins/">jenkins</a></li><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/redis/">redis</a></li><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/shiro/">shiro</a></li><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/spingMVC/">spingMVC</a></li><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/spring-cloud/">spring cloud</a></li><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/spring-cloud/">spring-cloud</a></li><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/spring-secrity/">spring-secrity</a></li><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/springMVC/">springMVC</a></li><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/springboot/">springboot</a></li><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/生活/">生活</a></li></ul>
    </div>
  </div>


  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Tag Cloud</h3>
    <div class="widget tagcloud">
      <a href="/org/tags/SVN/" style="font-size: 12px;">SVN</a> <a href="/org/tags/Spring-secrity/" style="font-size: 10px;">Spring-secrity</a> <a href="/org/tags/hexo/" style="font-size: 10px;">hexo</a> <a href="/org/tags/hibenrate/" style="font-size: 10px;">hibenrate</a> <a href="/org/tags/jekyll/" style="font-size: 10px;">jekyll</a> <a href="/org/tags/jenkins/" style="font-size: 10px;">jenkins</a> <a href="/org/tags/redis/" style="font-size: 16px;">redis</a> <a href="/org/tags/shiro/" style="font-size: 18px;">shiro</a> <a href="/org/tags/spingMVC/" style="font-size: 10px;">spingMVC</a> <a href="/org/tags/spring-cloud/" style="font-size: 10px;">spring cloud</a> <a href="/org/tags/spring-cloud/" style="font-size: 10px;">spring-cloud</a> <a href="/org/tags/spring-secrity/" style="font-size: 12px;">spring-secrity</a> <a href="/org/tags/springMVC/" style="font-size: 14px;">springMVC</a> <a href="/org/tags/springboot/" style="font-size: 20px;">springboot</a> <a href="/org/tags/生活/" style="font-size: 10px;">生活</a>
    </div>
  </div>

  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Archives</h3>
    <div class="widget">
      <ul class="archive-list"><li class="archive-list-item"><a class="archive-list-link" href="/org/archives/2018/11/">November 2018</a></li><li class="archive-list-item"><a class="archive-list-link" href="/org/archives/2018/10/">October 2018</a></li></ul>
    </div>
  </div>


  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Recent Posts</h3>
    <div class="widget">
      <ul>
        
          <li>
            <a href="/org/2018/11/27/redis07-zookeeper-kafka集群部署以及如何使用简单介绍/">redis07-zookeeper+kafka集群部署以及如何使用简单介绍</a>
          </li>
        
          <li>
            <a href="/org/2018/11/13/redis06-cluster实现高可用性/">redis06-cluster实现高可用性</a>
          </li>
        
          <li>
            <a href="/org/2018/11/12/redis05-在项目中搭建读写分-高可用-多master的redis-cluster集群/">redis05-在项目中搭建读写分+高可用+多master的redis cluster集群</a>
          </li>
        
          <li>
            <a href="/org/2018/11/05/在项目中用经典的三节点方式部署哨兵集群-笔记/">在项目中用经典的三节点方式部署哨兵集群-笔记</a>
          </li>
        
          <li>
            <a href="/org/2018/11/05/redis哨兵的多个核心底层原理-笔记/">redis哨兵的多个核心底层原理-笔记</a>
          </li>
        
      </ul>
    </div>
  </div>

  
</aside>
        
      </div>
      <footer id="footer">
  
  <div class="outer">
    <div id="footer-info" class="inner">
      &copy; 2018 John Doe<br>
      Powered by <a href="http://hexo.io/" target="_blank">Hexo</a>
    </div>
  </div>
</footer>
    </div>
    <nav id="mobile-nav">
  
    <a href="/org/" class="mobile-nav-link">Home</a>
  
    <a href="/org/archives" class="mobile-nav-link">Archives</a>
  
</nav>
    

<script src="//code.jquery.com/jquery-2.0.3.min.js"></script>


  <link rel="stylesheet" href="/org/fancybox/jquery.fancybox.css">
  <script src="/org/fancybox/jquery.fancybox.pack.js"></script>


<script src="/org/js/script.js"></script>



  </div>
</body>
</html>